package cn.sccdlg.mybatis2annotation.dao;

import cn.sccdlg.mybatis2annotation.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/10/15 23:38
 * 用户的持久层接口
 * 在mybatis中针对,CRUD一共有四个注解
 *   @Select @Insert @Update @Delete
 */
@Mapper
public interface IUserDao {

    /**
     * 查询所有用户
     * @return
     */
    @Select("select * from user")
    @Results(id="userMap",
            value= {
                    @Result(id=true,column="id",property="userId"),
                    @Result(column="username",property="userName"),
                    @Result(column="sex",property="userSex"),
                    @Result(column="address",property="userAddress"),
                    @Result(column="birthday",property="userBirthday")
            })
    List<User> findAll();

    /**
     * 保存用户
     * @param user
     * @return
     */
    @Insert("insert into user(username,address,sex,birthday) " +
            "values(#{userName},#{userAddress},#{userSex},#{userBirthday})")
    @SelectKey(keyColumn="id", keyProperty="userId", resultType=Integer.class, before = false,
            statement = { "select last_insert_id()" })
    int saveUser(User user);

    /**
     * 更新用户
     * @param user
     */
    @Update("update user set username=#{userName},sex=#{userSex},birthday=#{userBirthday}," +
            "address=#{userAddress} where id=#{userId}")
    void updateUser(User user);

    /**
     * 删除用户
     * @param userId
     */
    @Delete("delete from user where id=#{userId} ")
    void deleteUser(Integer userId);

    /**
     * 根据id查询用户
     * @param userId
     * @return
     */
    @Select("select * from user  where id=#{userId} ")
    @ResultMap("userMap")
    User findById(Integer userId);

    /**
     * 根据用户名称模糊查询
     * @param username
     * @return
     */
//    @Select("select * from user where username like #{username} ")
    @Select("select * from user where username like '%${value}%' ")
    @ResultMap("userMap")
    List<User> findUserByName(String username);

    /**
     * 查询总用户数量
     * @return
     */
    @Select("select count(*) from user ")
    int findTotalUser();
}
